'use client'

import { useState, useEffect } from 'react'
import { useRouter } from 'next/navigation'
import { useSession } from 'next-auth/react'
import Button from '@/components/ui/Button'
import { toast } from 'react-hot-toast'

interface ExperimentListItem {
  id: string;
  title: string;
}

export default function NewAnnouncementPage() {
  const router = useRouter()
  const { data: session, status } = useSession()
  const [title, setTitle] = useState('')
  const [content, setContent] = useState('')
  const [experiments, setExperiments] = useState<ExperimentListItem[]>([])
  const [selectedExperimentId, setSelectedExperimentId] = useState('')
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState('')

  useEffect(() => {
    if (status === 'unauthenticated') {
      router.replace('/login') 
    } else if (status === 'authenticated') {
      if (session.user.role !== 'ADMIN' && session.user.role !== 'TEACHER') {
        toast.error('您没有权限访问此页面')
        router.replace('/') 
      } else {
        // 获取实验列表
        const fetchExperiments = async () => {
          try {
            // 假设的API端点，您可能需要根据实际情况调整
            const res = await fetch('/api/experiments?fields=id,title') 
            if (!res.ok) {
              throw new Error('获取实验列表失败')
            }
            const data = await res.json();
            // 假设API返回的数据结构是 { experiments: ExperimentListItem[] } 或者直接是 ExperimentListItem[]
            setExperiments(data.experiments || data || []) 
          } catch (err: any) {
            toast.error(err.message || '无法加载实验列表')
            setError('无法加载实验列表，请稍后重试或联系管理员。')
          }
        };
        fetchExperiments();
      }
    }
  }, [session, status, router])

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    if (!title.trim() || !content.trim()) {
      setError('标题和内容不能为空')
      return
    }
    if (!selectedExperimentId) {
      setError('请选择一个关联的实验')
      toast.error('请选择一个实验');
      return
    }

    setLoading(true)
    setError('')

    try {
      const response = await fetch('/api/announcements', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          title,
          content,
          experimentId: selectedExperimentId,
        }),
      })

      if (!response.ok) {
        const data = await response.json()
        throw new Error(data.message || '创建公告失败')
      }

      toast.success('公告发布成功！')
      router.push('/') 
    } catch (err: any) {
      setError(err.message || '创建公告失败，请稍后重试')
      toast.error(err.message || '创建公告失败')
    } finally {
      setLoading(false)
    }
  }

  if (status === 'loading' || (status === 'authenticated' && experiments.length === 0 && !error)) {
    // 在会话加载完成且用户有权限后，如果实验列表为空且没有错误（意味着还在尝试加载或确实没有实验），显示加载状态
    return <div className="flex justify-center items-center min-h-screen">加载中...</div>
  }
  
  // 权限检查已在useEffect中处理重定向，这里可以再次确认以防万一
  if (status === 'unauthenticated' || (session && session.user.role !== 'ADMIN' && session.user.role !== 'TEACHER')) {
    return null; // 或者一个更明确的无权限提示，虽然useEffect应该已经跳转了
  }

  return (
    <div className="min-h-screen bg-gray-100 py-8 px-4 sm:px-6 lg:px-8">
      <div className="max-w-2xl mx-auto">
        <h1 className="text-3xl font-bold text-gray-900 mb-6 text-center">发布新公告</h1>
        
        {error && (
          <div className="mb-4 p-3 bg-red-100 text-red-700 rounded-md">
            {error}
          </div>
        )}

        <form onSubmit={handleSubmit} className="bg-white shadow-md rounded-lg p-8 space-y-6">
          <div>
            <label htmlFor="experiment" className="block text-sm font-medium text-gray-700">
              关联实验 <span className="text-red-500">*</span>
            </label>
            <select 
              id="experiment" 
              value={selectedExperimentId}
              onChange={(e) => setSelectedExperimentId(e.target.value)}
              className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm p-2"
              required
            >
              <option value="" disabled>-- 请选择一个实验 --</option>
              {experiments.map(exp => (
                <option key={exp.id} value={exp.id}>{exp.title}</option>
              ))}
            </select>
            {experiments.length === 0 && !error && status === 'authenticated' && (
                <p className="text-sm text-gray-500 mt-1">正在加载实验列表或暂无可选实验...</p>
            )}
          </div>

          <div>
            <label htmlFor="title" className="block text-sm font-medium text-gray-700">
              公告标题 <span className="text-red-500">*</span>
            </label>
            <input
              type="text"
              id="title"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm p-2"
              required
            />
          </div>

          <div>
            <label htmlFor="content" className="block text-sm font-medium text-gray-700">
              公告内容 <span className="text-red-500">*</span>
            </label>
            <textarea
              id="content"
              value={content}
              onChange={(e) => setContent(e.target.value)}
              rows={6}
              className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring-primary-500 sm:text-sm p-2"
              required
            />
          </div>
          
          <div className="flex justify-end">
            <Button type="button" variant="secondary" onClick={() => router.back()} disabled={loading} className="mr-3">
              取消
            </Button>
            <Button type="submit" variant="primary" disabled={loading || experiments.length === 0}>
              {loading ? '发布中...' : '确认发布'}
            </Button>
          </div>
        </form>
      </div>
    </div>
  )
} 